import { createRouter, createWebHistory, RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
import { useGlobalStore } from '@/pinia/modules/global';

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home/index.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
  },
  // 添加更多路由
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 全局前置守卫
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  const globalStore = useGlobalStore();
  const token = globalStore.token || localStorage.getItem('token'); // 从 Pinia Store 或本地存储中获取 token
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth); // 检查目标路由是否需要认证
console.log(requiresAuth,'requiresAuth');
console.log(token,'token');

  if (requiresAuth && !token) {
    // 如果目标路由需要认证且用户未登录，则重定向到登录页面
    next({ name: 'Login' });
  } else {
    // 否则继续导航
    next();
  }
});

export default router;